package com.lf.freezingpoint.common.security.handler;

import com.alibaba.fastjson2.JSONObject;
import com.lf.freezingpoint.common.entity.R;
import com.lf.freezingpoint.common.security.filter.JWTAuthenticationFilter;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.logging.Logger;

/**
 * 自定义jwt认证异常,处理已经认证过的用户访问无权限资源时的异常
 */
@Component
public class JWTAccessDeniedHandler implements AccessDeniedHandler {
    private static final Logger logger = Logger.getLogger(JWTAccessDeniedHandler.class.toString());

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {

        response.setCharacterEncoding("utf-8");
        response.setContentType("json/javascript;charset=utf-8");
        if ("Access Denied".equals(accessDeniedException.getMessage())) {
            response.getWriter().print(JSONObject.toJSONString(R.fail("权限不足，拒绝访问")));
        } else {
            response.getWriter().print(JSONObject.toJSONString(R.fail(accessDeniedException.getMessage())));
        }
        logger.info("JWTAccessDeniedHandler 异常处理");
    }
}
